package com.weetop.cfw.home_page.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.*
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.RegexUtils
import com.kongzue.dialog.v3.BottomMenu
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.weetop.cfw.R
import com.weetop.cfw.base.presenter.imp.PlantSalePublishPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.PlantSalePublishView
import com.weetop.cfw.bean.*
import com.weetop.cfw.callback.RxJavaCallBack
import com.weetop.cfw.constants.Constants
import com.weetop.cfw.home_page.adapter.BuildTypeDialog1
import com.weetop.cfw.home_page.adapter.IndustryDataDialog1
import com.weetop.cfw.home_page.utils.FullyGridLayoutManager
import com.weetop.cfw.home_page.utils.GridImageAdapter
import com.weetop.cfw.utils.*
import kotlinx.android.synthetic.main.activity_plant_sale_publish.*
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editAreaCovered
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editBuildStruct
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editContacts
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editFixedTelephone
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editFloor
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editFloorHeight
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editPhoneNumber
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editPrice
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editPublishInfoDesc
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editPublishInfoTitle
import kotlinx.android.synthetic.main.activity_plant_sale_publish.editRentOutTotalArea
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageChoosePhotoLogo
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem1
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem2
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem3
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem4
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem5
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem6
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem7
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem8
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageClearImageItem9
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imagePublishBack
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem1
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem2
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem3
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem4
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem5
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem6
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem7
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem8
import kotlinx.android.synthetic.main.activity_plant_sale_publish.imageUploadImageItem9
import kotlinx.android.synthetic.main.activity_plant_sale_publish.rcyshow
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativeAddressDetail
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativeAddressLocation
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativeAloneCourtyard
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativeAreaClassificationContainer
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativeBuildType
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativeHaveElevator
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativeIndustryContainer
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativePublishAddImageContainer
import kotlinx.android.synthetic.main.activity_plant_sale_publish.relativePublishSite
import kotlinx.android.synthetic.main.activity_plant_sale_publish.rlCover
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textAddressDetail
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textAddressLocation
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textAloneCourtyard
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textAreaClassification
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textBuildType
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textChoosePhotoLabel
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textChoosePhotoTip
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textHaveElevator
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textIndustry
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textPublishSite
import kotlinx.android.synthetic.main.activity_plant_sale_publish.textUploadImagesNumber
import kotlinx.android.synthetic.main.activity_publish.*
import org.angmarch.views.NiceSpinner

/**
 * 厂房出售界面
 */
class PlantSalePublishActivity : CommonBaseActivity(), View.OnClickListener, PlantSalePublishView {

    companion object {
        private const val EDIT_PUBLISH = "EDIT_PUBLISH"//是编辑还是新建 true:编辑 false:新建
        private const val IS_WORKSHOP_OR_WAREHOUSE =
            "IS_WORKSHOP_OR_WAREHOUSE"//是厂房还是仓库 true:厂房 false:仓库
        private const val INFOID = "INFOID"

        fun startPlantSalePublishActivity(
            context: Context,
            editPublish: Boolean,
            isWorkShopOrWarehouse: Boolean
        ) {
            val intent = Intent(context, PlantSalePublishActivity::class.java)
            intent.putExtra(EDIT_PUBLISH, editPublish)
            intent.putExtra(IS_WORKSHOP_OR_WAREHOUSE, isWorkShopOrWarehouse)
            ActivityUtils.startActivity(intent)
        }

        fun startPlantSalePublishActivity(
            context: Context,
            editPublish: Boolean,
            isWorkShopOrWarehouse: Boolean,
            infoid: Int
        ) {
            val intent = Intent(context, PlantSalePublishActivity::class.java)
            intent.putExtra(EDIT_PUBLISH, editPublish)
            intent.putExtra(IS_WORKSHOP_OR_WAREHOUSE, isWorkShopOrWarehouse)
            intent.putExtra(INFOID, infoid)
            ActivityUtils.startActivity(intent)
        }

    }

    private var maxSelectedNumber = 1//最多上传的图片数量

    private var longitude: String = ""//厂房、仓库所处位置经度
    private var latitude: String = ""//厂房、仓库所处位置维度

    private var industryId: String = "-1"//行业ID
    private var industryName: String = ""//行业名称
    private var areaId: String = "-1"//区域ID
    private var acrId: String = "-1"//面积分类ID
    private var cityId: Int = -1//选择的发布站点对应的ID
    private var siteId: Int = -1//站点ID

    //上传厂房仓库图片的集合
    private var uploadImagesList = ArrayList<LocalMedia>()
    private val workshopDetailImageList = ArrayList<String>()

    private lateinit var plantSalePublishPresenterImp: PlantSalePublishPresenterImp

    private lateinit var detailAddressAlertDialog: AlertDialog
    private lateinit var buildTypeDialog: BuildTypeDialog1
    private lateinit var industryDataDialog: IndustryDataDialog1

    private lateinit var detailAddressAlertDialogView: View
    private lateinit var districtAndCountySpinner: NiceSpinner
    private lateinit var editDetailAddress: EditText

    private lateinit var districtAndCountyList: ArrayList<String>

    private var industryStr: String = ""//行业字符串
    private var industryIdStr: String = ""//行业ID字符串

    //上传给后台的HashMap集合
    private val publishParamMap = HashMap<String, String>()


    private var isMotify: Boolean = false
    private var motifyInfoId: Int = 0

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.rlBuildingTypeSale -> {
                chooseBuildingType()
                rlBuildingTypeSale.setEnabled(false)
            }
            R.id.imagePublishBack -> ActivityUtils.finishActivity(this)
            R.id.imageChoosePhotoLogo, R.id.textChoosePhotoLabel, R.id.textChoosePhotoTip -> PictureSelectorUtils.openAlbumAndCamera(
                this,
                (9 - workshopDetailImageList.size)

            )
            R.id.relativeAloneCourtyard -> showAloneCourtyardBottomMenu()
            R.id.relativeHaveElevator -> showHaveElevatorBottomMenu()
            R.id.relativePublishSite -> plantSalePublishPresenterImp.getAllSitesData(this)
            R.id.relativeAddressDetail -> plantSalePublishPresenterImp.getDistrictAndCountyData(
                this,
                cityId
            )
            R.id.relativeHouseLicense -> showHaveHouseLicenseBottomMenu()
            R.id.relativeLandLicense -> showHaveLandLicenseBottomMenu()
            R.id.relativeIndustryContainer -> {
                plantSalePublishPresenterImp.getIndustryList(this)
                relativeIndustryContainer.setEnabled(false)
            }
            R.id.relativeAreaClassificationContainer -> plantSalePublishPresenterImp.areaClassificationList(
                this
            )
            R.id.relativeBuildType -> plantSalePublishPresenterImp.getBuildType(this)
            R.id.imageUploadImageItem1, R.id.imageUploadImageItem2, R.id.imageUploadImageItem3, R.id.imageUploadImageItem4,
            R.id.imageUploadImageItem5, R.id.imageUploadImageItem6, R.id.imageUploadImageItem7, R.id.imageUploadImageItem8, R.id.imageUploadImageItem9 -> PictureSelectorUtils.openAlbumAndCamera(
                this,
                1
            )
            R.id.relativeAddressLocation -> {
                val mapIntent = Intent(this@PlantSalePublishActivity, BaiDuMapActivity::class.java)
                startActivityForResult(mapIntent, 0)
            }
            R.id.imageClearImageItem1 -> {
                if (uploadImagesList.size >= 1) {
                    removePic(0, imageClearImageItem1, imageUploadImageItem1)
                }
            }
            R.id.imageClearImageItem2 -> {
                if (uploadImagesList.size >= 2) {
                    removePic(1, imageClearImageItem2, imageUploadImageItem2)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem2,
                        imageUploadImageItem2
                    )
                }
            }
            R.id.imageClearImageItem3 -> {
                if (uploadImagesList.size >= 3) {
                    removePic(2, imageClearImageItem3, imageUploadImageItem3)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem3,
                        imageUploadImageItem3
                    )
                }
            }
            R.id.imageClearImageItem4 -> {
                if (uploadImagesList.size >= 4) {
                    removePic(3, imageClearImageItem4, imageUploadImageItem4)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem4,
                        imageUploadImageItem4
                    )
                }
            }
            R.id.imageClearImageItem5 -> {
                if (uploadImagesList.size >= 5) {
                    removePic(4, imageClearImageItem5, imageUploadImageItem5)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem5,
                        imageUploadImageItem5
                    )
                }
            }
            R.id.imageClearImageItem6 -> {
                if (uploadImagesList.size >= 6) {
                    removePic(5, imageClearImageItem6, imageUploadImageItem6)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem6,
                        imageUploadImageItem6
                    )
                }
            }
            R.id.imageClearImageItem7 -> {
                if (uploadImagesList.size >= 7) {
                    removePic(6, imageClearImageItem7, imageUploadImageItem7)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem7,
                        imageUploadImageItem7
                    )
                }
            }
            R.id.imageClearImageItem8 -> {
                if (uploadImagesList.size >= 8) {
                    removePic(7, imageClearImageItem8, imageUploadImageItem8)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem8,
                        imageUploadImageItem8
                    )
                }
            }
            R.id.imageClearImageItem9 -> {
                if (uploadImagesList.size >= 9) {
                    removePic(8, imageClearImageItem9, imageUploadImageItem9)
                } else {
                    removePic(
                        uploadImagesList.size - 1,
                        imageClearImageItem9,
                        imageUploadImageItem9
                    )
                }
            }
            R.id.btnMakeSurePublish -> {
                when {
                    textPublishSite.text.toString() == "请选择" -> {
                        showNativeShortToast("请选择发布站点")
                    }
                    textAddressDetail.text.toString() == "请选择" -> {
                        showNativeShortToast("请选择详细地址")
                    }
                    editPublishInfoTitle.text.toString().trim() == "" -> {
                        showNativeShortToast("请填写信息标题")
                    }
                    textHaveHouseLicense.text.toString() == "请选择" -> {
                        showNativeShortToast("请选择有无房产证")
                    }
                    textLandLicense.text.toString() == "请选择" -> {
                        showNativeShortToast("请选择有无土地证")
                    }

                    textAloneCourtyard.text.toString() == "" -> {
                        showNativeShortToast("请选择是否独院")
                    }
                    textHaveElevator.text.toString() == "请选择" -> {
                        showNativeShortToast("请选择有无电梯")
                    }

                    editContacts.text.toString().trim() == "" -> {
                        showNativeShortToast("请填写联系人姓名")
                    }
                    !RegexUtils.isMobileSimple(editPhoneNumber.text.toString().trim()) -> {
                        showNativeShortToast("请填写正确手机号码")
                    }
                    buildingTypeIds.size == 0 -> {
                        showNativeShortToast("请选择建筑类型")
                    }
                    else -> {
                        if (textIndustry.text.toString() == "请选择") {
                            //大幽魂神话
                            publishParamMap["Vocid"] = ""
                            publishParamMap["vocname"] = ""
                        } else {
                            publishParamMap["Vocid"] = industryIdStr.dropLast(1)
                            publishParamMap["vocname"] = industryStr.dropLast(1)
                        }
//                        publishParamMap["Acrid"] = acrId
                        publishParamMap["Areaid"] = areaId
                        publishParamMap["siteid"] = siteId.toString()

                        publishParamMap["title"] = editPublishInfoTitle.text.toString().trim()
                        publishParamMap["Intid"] = "2"
                        var ids = ""
                        for (buildingTypeId in buildingTypeIds) {
                            ids += "$buildingTypeId,"
                        }
                        var names = ""
                        for (buildingTypeName in buildingTypeNames) {
                            names += "$buildingTypeName,"
                        }
                        publishParamMap["Typeid"] = ids.substring(0, ids.length - 1)
                        publishParamMap["Typename"] = names.substring(0, names.length - 1)

                        publishParamMap["Address"] = editDetailAddress.text.toString().trim()
                        publishParamMap["Totalarea"] = editRentOutTotalArea.text.toString().trim()
                        publishParamMap["Coverarea"] = editAreaCovered.text.toString().trim()
                        publishParamMap["Minarea"] = ""

                        if (textAloneCourtyard.text.toString() == "请选择") {
                            publishParamMap["Isalone"] = ""
                        } else {
                            publishParamMap["Isalone"] =
                                if (textAloneCourtyard.text.toString() == "是") "1" else "0"
                        }


                        publishParamMap["issublet"] = ""

                        publishParamMap["Useyearmin"] =
                            editBeginParticularYear.text.toString().trim()
                        publishParamMap["Useyearmax"] = editEndParticularYear.text.toString().trim()
                        publishParamMap["Price"] = editPrice.text.toString().trim()
                        publishParamMap["Punit"] = textPlantSalePublishUnit.text.toString()
                        publishParamMap["Maplat"] = latitude
                        publishParamMap["maplng"] = longitude
                        publishParamMap["Sstruct"] = editBuildStruct.text.toString().trim()
                        publishParamMap["Floor"] = editFloor.text.toString().trim()
                        publishParamMap["Fheight"] = editFloorHeight.text.toString().trim()

                        if (textHaveHouseLicense.text.toString() == "请选择") {
                            publishParamMap["Housecer"] = ""
                        } else {
                            publishParamMap["Housecer"] =
                                if (textHaveHouseLicense.text.toString() == "有") "1" else "0"
                        }

                        if (textLandLicense.text.toString() == "请选择") {
                            publishParamMap["landcer"] = ""
                        } else {
                            publishParamMap["landcer"] =
                                if (textHaveHouseLicense.text.toString() == "有") "1" else "0"
                        }

                        if (textHaveElevator.text.toString() == "请选择") {
                            publishParamMap["Haslift"] = ""
                        } else {
                            publishParamMap["Haslift"] =
                                if (textHaveElevator.text.toString() == "有") "1" else "0"
                        }

                        publishParamMap["Linkman"] = editContacts.text.toString().trim()
                        publishParamMap["Phone"] = editFixedTelephone.text.toString().trim()
                        publishParamMap["Mobile"] = editPhoneNumber.text.toString().trim()
                        publishParamMap["Content"] =
                            generateHtmlTemplate(editPublishInfoDesc.text.toString().trim())

                        if (workshopDetailImageList.size >= 1) {
                            publishParamMap["Imgfile"] = workshopDetailImageList[0]
                        } else {
                            publishParamMap["Imgfile"] = ""
                        }

                        var imglist: String = ""

                        for (i in workshopDetailImageList.indices) {
                            if (i != 0) {
                                imglist += workshopDetailImageList[i] + ","
                            }
                        }
//                        for (s in workshopDetailImageList) {
//                            imglist += s + ","
//                        }
                        if (imglist.length > 1) {
                            publishParamMap["Imglist"] =
                                imglist.substring(0, imglist.length - 1)
                        } else {
                            publishParamMap["Imglist"] = ""
                        }
                        plantSalePublishPresenterImp.publishLeaseSaleInformation(
                            this@PlantSalePublishActivity,
                            publishParamMap
                        )
                    }
                }
            }
        }
    }

    private var buildingTypeIds = ArrayList<String>()
    private var buildingTypeNames = ArrayList<String>()
    private fun chooseBuildingType() {
        RxJavaUtils.useInAppCompatActivityOnDestory(
            RetrofitUtils.getApi().generalCodeTable(1200),
            this@PlantSalePublishActivity,
            object : RxJavaCallBack<GeneralCodeTableBean>() {
                override fun onSuccess(t: GeneralCodeTableBean?) {
                    if (t != null) {

                        val industryInfoList = t.data

//                        var baseAdapter =
//                            ChooseAdapter(industryInfoList as java.util.ArrayList<GeneralCodeTableBean.DataBean>)
//
//                        BottomMenu.show(this@PlantSalePublishActivity, baseAdapter) { text, index ->
//
//
//                            if (textBuildingTypeSale.text.toString().contains(industryInfoList[index].codename)) {
//                                buildingTypeIds.remove(industryInfoList[index].codeid.toString())
//                                buildingTypeNames.remove(industryInfoList[index].codename)
//                            } else {
//                                buildingTypeIds.add(industryInfoList[index].codeid.toString())
//                                buildingTypeNames.add(industryInfoList[index].codename)
//                            }
//
//                            var textshow = ""
//                            for (buildingTypeName in buildingTypeNames) {
//                                textshow += "${buildingTypeName},"
//                            }
//                            textBuildingTypeSale.text = textshow
//                        }

                        val buildKindArray = ArrayList<String>()
                        val list1 = ArrayList<Boolean>()

                        industryInfoList.forEach { dataBean ->
                            buildKindArray.add(dataBean.codename)
                            list1.add(false)
                        }
                        rlBuildingTypeSale.setEnabled(true)
                        buildTypeDialog =
                            BuildTypeDialog1(
                                this@PlantSalePublishActivity,
                                t.data,
                                buildKindArray,
                                list1,
                                "选择建筑类型"
                            )
                        buildTypeDialog.show()

                    }
                }

                override fun onRequestError(t: GeneralCodeTableBean?) {
                    super.onRequestError(t)
                    rlBuildingTypeSale.setEnabled(true)
                }

            })
    }

    private inner class ChooseAdapter(infos: java.util.ArrayList<GeneralCodeTableBean.DataBean>) :
        BaseAdapter() {
        private var infos = java.util.ArrayList<GeneralCodeTableBean.DataBean>()

        init {
            this.infos = infos
        }

        override fun getCount(): Int {
            return infos.size
        }

        override fun getItem(position: Int): Any? {
            return infos[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
            var view =
                View.inflate(this@PlantSalePublishActivity, R.layout.item_bottom_menu_ios, null)
            var text = view.findViewById<TextView>(R.id.text)
            text.text = infos.get(position).codename
            if (textBuildingTypeSale.text.contains(infos.get(position).codename)) {
                text.setTextColor(Color.parseColor("#ff0000"))
            } else {
                text.setTextColor(Color.parseColor("#0000ff"))
            }

            return view
        }
    }

    override fun getLayoutId() = R.layout.activity_plant_sale_publish

    override fun initView(savedInstanceState: Bundle?) {
        isMotify = intent.getBooleanExtra("isMotify", false)
        motifyInfoId = intent.getIntExtra("motifyInfoId", 0)

        plantSalePublishPresenterImp = PlantSalePublishPresenterImp()
        plantSalePublishPresenterImp.attachView(this)

        detailAddressAlertDialogView =
            View.inflate(this, R.layout.layout_detail_address_alert_dialog, null)
        districtAndCountySpinner =
            detailAddressAlertDialogView.findViewById(R.id.districtAndCountySpinner)
        editDetailAddress = detailAddressAlertDialogView.findViewById(R.id.editDetailAddress)
        setViewsOnClickListener(
            this,
            imageClearImageItem1,
            imageClearImageItem2,
            imageClearImageItem3,
            imageClearImageItem4,
            imageClearImageItem5,
            imageClearImageItem6,
            imageClearImageItem7,
            imageClearImageItem8,
            imageClearImageItem9,
            relativeAddressLocation,
            btnMakeSurePublish,
            textChoosePhotoLabel,
            textChoosePhotoTip,
            relativeAreaClassificationContainer,
            relativeIndustryContainer,
            imagePublishBack,
            imageChoosePhotoLogo,
            relativeAloneCourtyard,
            relativeHaveElevator,
            relativePublishSite,
            relativeAddressDetail,
            relativeHouseLicense,
            relativeLandLicense,
            relativeBuildType,
            imageUploadImageItem1,
            imageUploadImageItem2,
            imageUploadImageItem3,
            imageUploadImageItem4,
            imageUploadImageItem5,
            imageUploadImageItem6,
            imageUploadImageItem7,
            imageUploadImageItem8,
            imageUploadImageItem9,
            rlBuildingTypeSale
        )

        initDetailAddressDialog()
        if (isMotify) {
            tvDesc.visibility = View.GONE
            editPublishInfoDesc.visibility = View.GONE
            relativePublishAddImageContainer.visibility = View.GONE
            getMotifyDetail()
        }
    }

    private fun getMotifyDetail() {
        RxJavaUtils.useInAppCompatActivityOnDestory(
            RetrofitUtils.getApi().workshopWarehouseDetailData(
                motifyInfoId
            ), this, object :
                RxJavaCallBack<WorkshopWarehouseDetailBean>() {
                override fun onSuccess(t: WorkshopWarehouseDetailBean?) {
                    if (t != null) {
                        //站点
                        textPublishSite.text = t.sitename
                        if (t.siteid != "")
                            siteId = t.siteid.toInt()
                        //详细地址
                        //详细地址
                        areaId = t.areaid
                        cityId = t.cityid.toInt()
                        editDetailAddress.setText(t.areaname + " " + t.address)

                        textAddressDetail.text = t.address
                        //信息标题
                        editPublishInfoTitle.setText(t.title)
                        //行业
                        industryIdStr = t.vocid.toString()
                        industryStr = t.vocname
                        textIndustry.text = t.vocname
                        //厂房占地面积
                        editAreaCovered.setText(t.coverarea)
                        textBuildingTypeSale.text = t.typename
                        buildingTypeIds = t.typeid.split(",") as ArrayList<String>

                        buildingTypeNames = t.typename.split(",") as ArrayList<String>
                        if (t.housecer == "1") {
                            textHaveHouseLicense.text = "有"
                        } else {
                            textHaveHouseLicense.text = "无"
                        }
                        if (t.landcer == "1") {
                            textLandLicense.text = "有"
                        } else {
                            textLandLicense.text = "无"
                        }

                        //出租总面积
                        editRentOutTotalArea.setText(t.totalarea)
                        //建筑面积
                        editRentalArea.setText(t.minarea)
                        if (t.useyearmin != null && t.useyearmin != "")
                            editBeginParticularYear.setText(t.useyearmin)
                        if (t.useyearmax != null && t.useyearmax != "")
                            editEndParticularYear.setText(t.useyearmax)


                        editPrice.setText(t.price)
                        editBuildStruct.setText(t.struct)
                        editFloor.setText(t.floor)
                        editFloorHeight.setText(t.fheight)
                        if (t.alone.equals("独院")) {
                            textAloneCourtyard.text = "是"
                        } else {
                            textAloneCourtyard.text = "否"
                        }
                        if (t.lift.equals("电梯")) {
                            textHaveElevator.text = "是"
                        } else {
                            textHaveElevator.text = "否"
                        }
                        editContacts.setText(t.linkman)
                        editPhoneNumber.setText(t.mobile)

                        if (t.phone != null)
                            editFixedTelephone.setText(t.phone)

                    }
                }

                override fun onRequestError(t: WorkshopWarehouseDetailBean?) {
                    super.onRequestError(t)
                }

                override fun onErrorResponse(throwable: Throwable?) {
                    super.onErrorResponse(throwable)
                }
            })
    }


    /**
     * 生成HTML模板
     */
    private fun generateHtmlTemplate(contentDesc: String): String {
        var html = ""
        return if (workshopDetailImageList.size >= 2) {
            var htmlDoc = ""
            for (item in workshopDetailImageList) {
//                if (workshopDetailImageList.indexOf(item) != 0) {
//                    htmlDoc =
//                        "<img src=\"${item}\" style=\"vertical-align: middle; max-width: 100%;\">"
//                    htmlDoc += htmlDoc
//                }
            }
            html =
                "<p style=\"margin-top: 0px; margin-bottom: 0px; padding: 0px 0px 24px; text-align: center; color: rgb(27, 27, 27); font-family: &quot;Microsoft YaHei&quot;, &quot;Hiragino Sans GB&quot;, &quot;WenQuanYi Micro Hei&quot;, 微软雅黑, 宋体, sans-serif; font-size: 18px; white-space: normal; background-color: rgb(255, 255, 255);\"><span style=\"color: rgb(27, 27, 27); font-family: &quot;Microsoft YaHei&quot;, &quot;Hiragino Sans GB&quot;, &quot;WenQuanYi Micro Hei&quot;, 微软雅黑, 宋体, sans-serif; font-size: 18px; text-indent: 36px; white-space: normal; background-color: rgb(255, 255, 255);\">${contentDesc}</span></p><p style=\"margin-top: 0px; margin-bottom: 0px; padding: 0px 0px 24px; text-align: center; color: rgb(27, 27, 27); font-family: &quot;Microsoft YaHei&quot;, &quot;Hiragino Sans GB&quot;, &quot;WenQuanYi Micro Hei&quot;, 微软雅黑, 宋体, sans-serif; font-size: 18px; white-space: normal; background-color: rgb(255, 255, 255);\">${htmlDoc}</p>"
            LogUtils.dTag("generateHtmlTemplate", html)
            return html
        } else {
            ""
        }
    }

    /**
     * 移除图片
     * @param position 移除的图片数据在集合中的下标
     * @param clearImage 移除图片的按钮
     * @param imageUploadImageItem
     */
    private fun removePic(position: Int, clearImage: ImageView, imageUploadImageItem: ImageView) {
        uploadImagesList.removeAt(position)

        workshopDetailImageList.removeAt(position)

        clearImage.visibility = View.INVISIBLE

        GlideUtils.loadImage(
            imageUploadImageItem,
            R.mipmap.upload_img_place_holder,
            imageUploadImageItem
        )

        imageUploadImageItem.isEnabled = true

        maxSelectedNumber += 1

        textUploadImagesNumber.text = "${uploadImagesList.size}/9张"
    }

    lateinit var mAdapter: GridImageAdapter

    override fun initData(savedInstanceState: Bundle?) {

        publishParamMap["Token"] = MMKVUtils.getToken()

        if (intent!!.getBooleanExtra(EDIT_PUBLISH, false)) {//编辑

        } else {//新建
            publishParamMap["Infoid"] = "0"
        }

        if (intent!!.getBooleanExtra(IS_WORKSHOP_OR_WAREHOUSE, true)) {
            textOfferForSalePublishTitle.text = "厂房出售"
        } else {
            textOfferForSalePublishTitle.text = "仓库出售"
        }

        plantSalePublishPresenterImp.getSiteInfoByCity(this, Constants.cityName)
        val manager = FullyGridLayoutManager(
            this,
            4, GridLayoutManager.VERTICAL, false
        )
        rcyshow.setLayoutManager(manager)
        mAdapter = GridImageAdapter(this, onAddPicClickListener)
        mAdapter.setSelectMax(9)
        rcyshow.setAdapter(mAdapter)
    }

    private val onAddPicClickListener = GridImageAdapter.onAddPicClickListener {
        PictureSelectorUtils.openAlbumAndCamera(this, 9 - workshopDetailImageList.size)
    }
    private var currentList = ArrayList<LocalMedia>()
    private var uploadPosition = 0

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片、视频、音频选择结果回调
                    val selectList = PictureSelector.obtainMultipleResult(data)
                    //将选择的图片数据集合添加到集合中
                    currentList.clear()
                    currentList.addAll(selectList)

                    uploadPosition = 0
                    if (currentList[0].isCompressed) {
                        plantSalePublishPresenterImp.uploadWorkshopDetailImage(
                            this@PlantSalePublishActivity,
                            currentList[0].compressPath
                        )
                    } else {
                        plantSalePublishPresenterImp.uploadWorkshopDetailImage(
                            this@PlantSalePublishActivity,
                            currentList[0].path
                        )
                    }
//                    for (item in selectList) {
//                        if (item.isCompressed) {
//                            plantSalePublishPresenterImp.uploadWorkshopDetailImage(
//                                this@PlantSalePublishActivity,
//                                item.compressPath
//                            )
//                        } else {
//                            plantSalePublishPresenterImp.uploadWorkshopDetailImage(
//                                this@PlantSalePublishActivity,
//                                item.path
//                            )
//                        }
//                    }


                }
            }
        }
    }

    /**
     * 根据经纬度获取详细地址信息
     */
    private fun getDetailAddressByLatLng(latLng: LatLng) {
        val geoCoder = GeoCoder.newInstance()
        geoCoder.setOnGetGeoCodeResultListener(object :
            OnGetGeoCoderResultListener {

            override fun onGetGeoCodeResult(p0: GeoCodeResult?) {

            }


            override fun onGetReverseGeoCodeResult(reverseGeoCodeResult: ReverseGeoCodeResult) {
                if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    // 没有检测到结果
                    return
                }
                val addressDetail = reverseGeoCodeResult.addressDetail
                //需要的地址信息就在AddressComponent 里
                textAddressLocation.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textAddressLocation.text =
                    "${addressDetail.province}${addressDetail.city}${addressDetail.district}${addressDetail.town}${addressDetail.street}${addressDetail.streetNumber}"
            }
        })
        geoCoder.reverseGeoCode(ReverseGeoCodeOption().location(latLng))
    }

    /**
     * 展示厂房是否是独院的底部对话框
     */
    private fun showAloneCourtyardBottomMenu() {
        BottomMenu.show(
            this@PlantSalePublishActivity,
            arrayOf("是", "否")
        ) { text, index ->
            textAloneCourtyard.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textAloneCourtyard.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    /**
     * 展示厂房是否有电梯的底部对话框
     */
    private fun showHaveElevatorBottomMenu() {
        BottomMenu.show(
            this@PlantSalePublishActivity,
            arrayOf("有", "无")
        ) { text, index ->
            textHaveElevator.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textHaveElevator.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    /**
     * 展示发布站点的底部对话框
     */
    private fun showPublishSiteBottomMenu(allSitesDataBean: List<AllSitesBean.DataBean>) {
        LogUtils.d("allSitesDataBean", allSitesDataBean)
        val sitesArray = ArrayList<String>()
        for (i in allSitesDataBean.indices) {
            sitesArray.add(allSitesDataBean[i].sitename)
            //LogUtils.e("sitename", allSitesDataBean[i].sitename)
        }

        BottomMenu.show(
            this@PlantSalePublishActivity,
            sitesArray
        ) { text, index ->
            siteId = allSitesDataBean[index].siteid
            cityId = allSitesDataBean[index].cityid

            textPublishSite.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textPublishSite.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    /**
     * 展示是否有房产证的底部对话框
     */
    private fun showHaveHouseLicenseBottomMenu() {
        BottomMenu.show(
            this@PlantSalePublishActivity,
            arrayOf("有", "无")
        ) { text, index ->
            textHaveHouseLicense.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textHaveHouseLicense.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    /**
     * 展示是否有土地证的底部对话框
     */
    private fun showHaveLandLicenseBottomMenu() {
        BottomMenu.show(
            this@PlantSalePublishActivity,
            arrayOf("有", "无")
        ) { text, index ->
            textLandLicense.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textLandLicense.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    /**
     * 展示建筑类型选择的底部对话框
     */
    private fun showBuildTypeBottomMenu(kindDataBeanList: List<KindBean.DataBean>) {
        val buildKindArray = ArrayList<String>()

        kindDataBeanList.forEach { dataBean ->
            buildKindArray.add(dataBean.codename)
        }

        LogUtils.d("buildKindArray", buildKindArray)
        BottomMenu.show(
            this@PlantSalePublishActivity,
            buildKindArray
        ) { text, index ->
            textBuildType.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            //返回参数 text 即菜单名称，index 即菜单索引
            textBuildType.text = Editable.Factory.getInstance().newEditable(text)
        }
    }

    public fun getSelectList(
        mList: java.util.ArrayList<String>,
        idList: java.util.ArrayList<String>
    ) {
        var buildTypeStr = ""
        buildingTypeIds.clear()
        buildingTypeNames.clear()
        for (i in mList.indices) {
            buildingTypeIds.add(idList[i])
            buildingTypeNames.add(mList[i])
            buildTypeStr = buildTypeStr + mList[i] + ","
        }
        textBuildingTypeSale.setTextColor(ColorUtils.getColor(R.color.colorAccent))
        textBuildingTypeSale.text = buildTypeStr

    }


    override fun onDestroy() {
        super.onDestroy()
        plantSalePublishPresenterImp.detachView()
    }

    /**
     * 所有分站数据获取成功
     */
    override fun getAllSitesDataSuccess(allSitesBean: AllSitesBean?) {
        if (allSitesBean != null) {
            LogUtils.d("allSitesBean", allSitesBean)
            showPublishSiteBottomMenu(allSitesBean.data)
        }
    }

    /**
     * 建筑类型数据获取成功
     */
    override fun getBuildKindDataSuccess(kindBean: KindBean?) {
        if (kindBean != null) {
            showBuildTypeBottomMenu(kindBean.data)
        }
    }

    /**
     * 出租出售信息发布成功
     */
    override fun leaseSaleInformationPublishSuccess(errorBean: PublishBean?) {
        if (errorBean != null) {
//            showNativeShortToast("发布成功")
//            ActivityUtils.finishActivity(this)

            showNativeShortToast(errorBean.message)
            var intent = Intent(this, AdPayToTopActivity::class.java)
            intent.putExtra("infoId", errorBean.infoid)
            startActivity(intent)
            finish()
        }
    }

    /**
     * 站点信息获取成功
     */
    override fun siteInfoGetSuccess(cityIdBean: CityIdBean?) {
        if (cityIdBean != null) {
            cityId = cityIdBean.cityid
            siteId = cityIdBean.siteid

            textPublishSite.setTextColor(ColorUtils.getColor(R.color.colorAccent))
            textPublishSite.text = cityIdBean.sitename
        }
    }

    /**
     * 县区信息获取成功
     */
    override fun getDistrictAndCountyDataSuccess(siteBean: SiteBean?) {
        if (siteBean != null) {
            districtAndCountyList = ArrayList<String>()
            for (item in siteBean.data) {
                districtAndCountyList.add(item.areaname)
            }
            districtAndCountySpinner.attachDataSource(districtAndCountyList)
            areaId = siteBean.data[0].areaid.toString()
            districtAndCountySpinner.setOnSpinnerItemSelectedListener { parent, view, position, id ->
                areaId = siteBean.data[position].areaid.toString()
            }
            detailAddressAlertDialog.show()
        }
    }

    /**
     * 行业数据获取成功
     */
    override fun industryDataGetSuccess(generalCodeTableBean: GeneralCodeTableBean?) {
//        if (generalCodeTableBean != null) {
//            val industry = ArrayList<String>()
//            val industryInfoList = generalCodeTableBean.data
//            for (itemIndustry in industryInfoList) {
//                industry.add(itemIndustry.codename)
//            }
//            LogUtils.eTag("industry", industry)
//            BottomMenu.show(this@PlantSalePublishActivity, industry) { text, index ->
//
//                industryId = generalCodeTableBean.data[index].codeid.toString()
//                industryName = generalCodeTableBean.data[index].codename
//
//                if (StringUtils.isEmpty(industryStr) || !industryStr.contains(industryName)) {
//                    industryIdStr += "${industryId},"
//                    industryStr += "${industryName},"
//                }
//
//                textIndustry.setTextColor(ColorUtils.getColor(R.color.colorAccent))
//                //返回参数 text 即菜单名称，index 即菜单索引
//                textIndustry.text =
//                    Editable.Factory.getInstance().newEditable(industryStr.dropLast(1))
//            }
//        }

        relativeIndustryContainer.setEnabled(true)
        if (generalCodeTableBean != null) {
            val buildKindArray = ArrayList<String>()
            val list1 = ArrayList<Boolean>()

            val industryInfoList = generalCodeTableBean.data
            for (itemIndustry in industryInfoList) {
                buildKindArray.add(itemIndustry.codename)
                list1.add(false)
            }
            industryDataDialog =
                IndustryDataDialog1(
                    this@PlantSalePublishActivity,
                    generalCodeTableBean.data,
                    buildKindArray,
                    list1,
                    "选择行业"
                )
            industryDataDialog.show()
        }
    }

    public fun getSelectList1(
        mList: java.util.ArrayList<String>,
        idList: java.util.ArrayList<String>
    ) {

        industryIdStr = ""
        industryStr = ""
        for (i in mList.indices) {
            industryStr = industryStr + mList[i] + ","
            industryIdStr = industryIdStr + idList[i] + ","
        }
        textIndustry.setTextColor(ColorUtils.getColor(R.color.colorAccent))
        textIndustry.text = industryStr

    }

    /**
     * 面积归类数据获取成功
     */
    override fun areaClassificationDataGetSuccess(generalCodeTableBean: GeneralCodeTableBean?) {
        if (generalCodeTableBean != null) {
            val areaClassification = ArrayList<String>()
            val areaClassificationInfoList = generalCodeTableBean.data
            for (itemIndustry in areaClassificationInfoList) {
                areaClassification.add(itemIndustry.codename)
            }
            LogUtils.eTag("areaClassification", areaClassification)
            BottomMenu.show(this@PlantSalePublishActivity, areaClassification) { text, index ->

                acrId = generalCodeTableBean.data[index].codeid.toString()

                textAreaClassification.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                //返回参数 text 即菜单名称，index 即菜单索引
                textAreaClassification.text = Editable.Factory.getInstance().newEditable(text)
            }
        }
    }

    /**
     * 上传图片成功
     */
    override fun uploadImageSuccess(imageUrl: String) {

        LogUtils.eTag("uploadImageSuccess", imageUrl)
//        workshopDetailImageList.add("${UrlConstants.baseUrl}${imageUrl}")
        workshopDetailImageList.add(imageUrl)
        uploadImagesList.add(currentList[uploadPosition])
        mAdapter.setList(uploadImagesList, workshopDetailImageList)

        if (uploadImagesList.size > 0) {
            rlCover.visibility = View.GONE
            rcyshow.visibility = View.VISIBLE
        } else {
            rlCover.visibility = View.VISIBLE
            rcyshow.visibility = View.GONE
        }
        mAdapter.notifyDataSetChanged()
        uploadPosition += 1

        if (uploadPosition + 1 <= currentList.size) {
            if (currentList[uploadPosition].isCompressed) {
                plantSalePublishPresenterImp.uploadWorkshopDetailImage(
                    this@PlantSalePublishActivity,
                    currentList[uploadPosition].compressPath
                )
            } else {
                plantSalePublishPresenterImp.uploadWorkshopDetailImage(
                    this@PlantSalePublishActivity,
                    currentList[uploadPosition].path
                )
            }
        } else {
            uploadPosition = 0
        }
    }

    override fun uploadImageError() {
        uploadPosition += 1
        if (uploadPosition + 1 <= currentList.size) {
            if (currentList[uploadPosition].isCompressed) {
                plantSalePublishPresenterImp.uploadWorkshopDetailImage(
                    this@PlantSalePublishActivity,
                    currentList[uploadPosition].compressPath
                )
            } else {
                plantSalePublishPresenterImp.uploadWorkshopDetailImage(
                    this@PlantSalePublishActivity,
                    currentList[uploadPosition].path
                )
            }
        } else {
            uploadPosition = 0
        }

    }


    /**
     * 初始化选择详细地址的对话框
     */
    private fun initDetailAddressDialog() {
        detailAddressAlertDialog = AlertDialog.Builder(this)
            .setCancelable(true)
            .setView(detailAddressAlertDialogView)
            .setPositiveButton(
                "确定"
            ) { dialog, which ->
                textAddressDetail.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textAddressDetail.text =
                    "${districtAndCountyList[districtAndCountySpinner.selectedIndex]} ${editDetailAddress.text.toString()
                        .trim()}"
            }
            .setNegativeButton("取消", null)
            .create()
    }

}
